/**
 * Created by lyp on 2017/8/1.
 */
$(document).ready(function(){
    user.layerDate();//调用时间插件
    user.loadTurnList();//加载数据表格
    user.bootstrapValidator();//表单验证
    user.searchTurn();//点击查询
    user.turnType();//调用工具类型接口
    user.turnOrganze();//调用工具类型接口
    user.Initfileinput();
    user.Initfileinput('uploadfile');//初始化插件
    var btnElement = '#stockSearchForm .dis, #toobar .dis';
    btnJurisdiction(btnElement);//查询当前用户的按钮权限
});
$(function(){
    $('#pdfBox').on('hide.bs.modal', function () {
        $("#media").attr("href","");  //查看pdf文件窗口关闭时清除a标签href属性
    });
})
var user = {};
(function(res){
    //fileinput插件
    res.Initfileinput = function(ctrlName,uploadUrl){
        var control = $('#' + ctrlName);
        control.fileinput({
            showCaption: true,//是否显示标题
            language:'zh',//设置语言
            showPreview:true,//是否显示预览
            showUpload:true,//是否显示上传按钮
            showRemove:true,//显示移除按钮
            showCancel:false,//隐藏取消按钮
            uploadAsync: true,//默认异步上传
            allowedFileExtensions: ['xlsx','xls'],
            uploadUrl:uploadUrl,//上传的地址(访问接口地址)
            showAjaxErrorDetails:false,//上传结果展示
            browseOnZoneClick: true,
            maxFileCount:5,
            uploadExtraData:function(){
                // var obj = {};
                // obj.datasort = $("#sjlx").val();
                // return obj;
            },//上传文件时额外传递的参数设置
            enctype: 'multipart/form-data',
            dropZoneEnabled:true,//是否显示拖拽区域
            maxFileCount: 5,//表示允许同时上传的最大文件个数
            minFileCount:1,
            layoutTemplates:{
                //actionDelete:'',
                actionUpload:'',
            }
        })
    }
    //导入文件
    res.Addfile  =function(){
        $("#AddInfo").modal("show");
    }
    //上传附件
    user.submitPic = function(){
        var form = new FormData(document.getElementById("form-file-add"));
        $.ajax({
            url:"../toolController/upLodeTool",
            type:"post",
            data:form,
            dataType:"json",
            processData:false,
            contentType:false,
            success:function(data){
                if (data.code == 0){
                    $("#AddInfo").modal("hide");
                    layer.msg(data.msg);
                    $("#turnOverList").bootstrapTable("refresh");
                }else{
                    var errData = data.errData;
                    $("#ToolErrorDialog").modal("show");
                    res.ToolErrorList(errData);
                    layer.msg(data.msg);
                }
            }
        });
    }
    //出错数据弹窗表格
    res.ToolErrorList=function(errData){
        var listError = $("#ToolErrorList .listError"),str = "";
        for(var i = 0; i<errData.length;i++){
            if(errData[i].type != null && errData[i].type!=''&& errData[i].type.length==32){
                var name = res.dataList(errData[i].type);
                errData[i].type = name;
            }
            if(errData[i].dimension != null && errData[i].dimension!=''&& errData[i].dimension.length==32){
                var name = res.dataList(errData[i].dimension);
                errData[i].dimension = name;
            }
            if(errData[i].status != null && errData[i].status!=''&& errData[i].status.length==32){
                var name = res.dataList(errData[i].status);
                errData[i].status = name;
            }
            if(errData[i].base != null && errData[i].base!=''&& errData[i].base.length==32){
                var name = res.dataList(errData[i].base);
                errData[i].base = name;
            }
            if(errData[i].manufactureDate != null && errData[i].manufactureDate !=''){
                var manufactureDate = errData[i].manufactureDate;
                manufactureDate = manufactureDate.substr(0,10);
            }else{
                var manufactureDate = errData[i].manufactureDate;
                manufactureDate = '';
            }
            str +=`<tr><td>${errData[i].type}</td>
                   <td>${errData[i].toolName}</td>
                   <td>${errData[i].no}</td>
                   <td>${errData[i].dimension}</td>
                   <td>${errData[i].deadWeight}</td>
                   <td>${errData[i].safeLoad}</td>
                   <td>${manufactureDate}</td>
                   <td>${errData[i].status}</td>
                   <td>${errData[i].base}</td>
                   <td>${errData[i].remark}</td>
                   <td>${errData[i].deviceId}</td></tr>`;
        }
        listError.html(str);
    };
    //错误数据返回中文名称
    res.dataList = function(name){
        var name2 = "";
        $.ajax({
            type: "POST",
            data:{id:name},
            async:false,
            url: '../sysCodeListController/getSysCodeList',
            success:function(res){
                var res = res.data;
                name2='';
                if(res!=null&&res.length>0){
                    name2 = res[0].name;
                }
            }
        })
        return name2;
    }
    //导出
    res.eaportData = function(){
        var type = $("#typeTurn").val();
        var toolName = $("#toolNameTurn").val();
        var status = $("#statusTurn").val();
        var base = $("#baseTurn").val();
        var numberTurn = $("#noTurns").val();
        $.ajax({
            type:"post",
            url:"../toolController/exportExcelTool",
            data:{
                "type":type,
                "toolName":toolName,
                "base":base,
                "status":status,
                "no":numberTurn
            },
            success:function(data){
                if(data.code== 0){
                    window.location.href = data.url;
                }
            }
        })
    }
    //表单验证
    res.bootstrapValidator=function(){
        $("#addTurnForm").bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                validating: 'glyphicon glyphicon-refresh'
            },
            fields:{
                type:{
                    validators: {
                        notEmpty: {
                            message: '请选择工具类型'
                        }
                    }
                },
                toolName:{
                    validators: {
                        notEmpty: {
                            message: '工具名称不能为空'
                        }
                    }
                },
                no:{
                    validators: {
                        notEmpty: {
                            message: '工具编号不能为空'
                        }
                    }
                },
                status:{
                    validators: {
                        notEmpty: {
                            message: '状态不能为空'
                        }
                    }
                },
                base:{
                    validators: {
                        notEmpty: {
                            message: '请选择归属地'
                        }
                    }
                },
                /*remark:{
                    validators: {
                        notEmpty: {
                            message: '请填写备注'
                        },
                        regexp: {
                            regexp: /([a-zA-Z0-9_]+)(.gif|.jpg|.jpeg|.GIF|.JPG|.JPEG|.png)/,
                            message: '图片格式不正确'
                        }
                    }
                }*/
            }
        });
    };
    //防止表单重复验证
    res.resetValidator=function(){
        $("form.required-validate").each(function() {
            var $form = $(this);
            $form.bootstrapValidator().on("success.form.bv",function(e){
                e.preventDefault();
            });
        });
    };
    //打开添加用户的窗口
    res.openAddTurn=function(){
        $("#addTurnForm").data('bootstrapValidator').destroy();
        $('#addTurnForm').data('bootstrapValidator', null);
        res.bootstrapValidator();
        $("#addUserDialog").modal("show");
        $("#changeUser").html("添加周转工具");
        var isTrue = true;
        res.resetTurnUser(isTrue);
        $("#organizationId,#phone,#email,#pwd,#zuserPwd,#userName").val("");
        $("#userType").val(0);
        $("#sex").val(0);
    };
    //提交添加用户的form表单
    res.submitTurnUser=function(){
        var $form = $('#addTurnForm');
        var data = $form.data('bootstrapValidator');
        if (data) {
            // 修复记忆的组件不验证
            data.validate();
            if (!data.isValid()) {
                return false;
            }
        }
        res.resetValidator();
        var manufactureDate = $("#manufactureDate").val();
        if(manufactureDate == null || manufactureDate == ''){
            $("#manufactureDate").val("");
        }
        var data = $("#addTurnForm").serialize();
        $.ajax({
            url:"../toolController/addOrUpdateTool",
            type:"post",
            data:data,
            dataType:"json",
            success:function(data){
                if (data.code==0){
                    $("#addUserDialog").modal("hide");
                    layer.msg(data.msg);
                    $("#turnOverList").bootstrapTable("refresh");
                    $('#addTurnForm').bootstrapValidator('resetForm', true);
                }else{
                    layer.msg(data.msg);
                }
            }
        });
    };
    //重置添加用户的form表单
    res.resetTurnUser=function(isTrue){
        $("#addTurnForm").find(":input").val("");
        $(".selectpicker").selectpicker('refresh');//刷新下拉框;
        $('#addTurnForm').bootstrapValidator('resetForm');//重置表单是重置表单验证
    };
    //数据列表
    res.loadTurnList=function(type,toolName,base,status,numberTurn){
        $('#turnOverList').bootstrapTable('destroy');/*表格加载前先销毁原有数据*/
        $('#turnOverList').bootstrapTable({
            method: 'POST',
            url:"../toolController/getToolList",
            queryParamsType:'',
            queryParams:function (params) {
                pageSize = params.pageSize;
                pageNum = params.pageNumber;
                return {
                    pageSize:pageSize,
                    pageNum:pageNum,
                    type:type,
                    toolName:toolName,
                    base:base,
                    status:status,
                    no:numberTurn
                }
            },
            contentType:"application/x-www-form-urlencoded; charset=UTF-8",
            cache: false,     // 不缓存
            striped: true,    // 隔行加亮
            pagination: true, //是否显示分页
            toolbar: '#toobar',//工具列
            singleSelect:true, //单选
            clickToSelect:true,
            pageSize: 10,
            pageNumber: 1,     //初始化加载第一页，默认第一页
            pageList: [5, 10, 20, 30, 50], //可供选择的每页的行数（*）
            sidePagination: "server",
            search: false,
            showRefresh: true,  //是否显示刷新按钮
            showColumns: true,
            columns:[
                {field: "select",title: "选择",checkbox: true,width: 60},
                {field: '',title: '序号',width: 60,align:"center",valign:"middle",formatter: function (value, row, index) {return index+1;}},
                {field:"type",title:"工具类型",align:"center",valign:"middle",sortable:"true"},
                {field:"toolName",title:"工具名称",align:"center",valign:"middle",sortable:"true"},
                {field:"no",title:"工具编号",align:"center",valign:"middle",sortable:"true"},
                {field:"status",title:"状态",align:"center",valign:"middle",sortable:"true"},
                {field:"base",title:"归属地",align:"center",valign:"middle",sortable:"true"},
                {field:"dimension",title:"尺寸",align:"center",valign:"middle",sortable:"true",visible: false},
                {field:"deadWeight",title:"自重",align:"center",valign:"middle",sortable:"true",visible: false},
                {field:"safeLoad",title:"安全载荷",align:"center",valign:"middle",sortable:"true",visible: false},
                {field:"manufactureDate",title:"生产日期",align:"center",valign:"middle",sortable:"true",visible: false,formatter: function (value) {
                    if(value==""||value==null){
                        return "";
                    }else{
                        var values = value.substring(0,10);
                        return values;
                    }
                }},
                {field:"remark",title:"备注",align:"center",valign:"middle",sortable:"true"},
                {field:"deviceId",title:"终端设备ID",align:"center",valign:"middle",sortable:"true",visible: false},
                {field:"cz",title:"操作",align:"center",valign:"middle",width:180,formatter: res.checkFormatter}

            ],
            onClickRow:function(row,ele){

            },
            formatLoadingMessage: function () {
                return "请稍等，正在加载中...";
            },
            formatNoMatches: function () {
                return '无符合条件的记录';
            },
            responseHandler: function(res) {
                var total ,rows;
                if (res!=null&&res.length!=0) {
                    total = res[0].total;
                    rows = res;
                }else {
                    total = 0;
                    rows = new Array();
                }
                return {
                    "total":total,//total,//总页数
                    "rows":rows  //数据
                };
            },
            onPostBody:function(){
                var btnElement = '.toolMag';
                btnJurisdiction(btnElement);//查询当前用户的按钮权限
            }
        });
    };
    // res.hidecolun = function(){
    //     $('#turnOverList').bootstrapTable('hideColumn', 'dimension');
    //     $('#turnOverList').bootstrapTable('hideColumn', 'deadWeight');
    //     $('#turnOverList').bootstrapTable('hideColumn', 'safeLoad');
    //     $('#turnOverList').bootstrapTable('hideColumn', 'remark');
    //     $('#turnOverList').bootstrapTable('hideColumn', 'deviceId');
    //     $('#turnOverList').bootstrapTable('hideColumn', 'manufactureDate');
    // }
    $(function () {
        //隐藏列
        $('#addUserDialog').on('hide.bs.modal', function () {
            //窗口关闭时重置表单验证
            $('#addTurnForm').bootstrapValidator('resetForm', true);
        })
    });
    //查看检验证书
    res.checkFormatter = function(value,row){
        var html = '<button type="button" class="dis toolMag btn btn-primary" value="管理证书检验工具" title="检验证书" onclick="user.ToolMangement(\''+row.no+'\');" > <span class="glyphicon glyphicon-list-alt"></span></button>&nbsp;&nbsp;&nbsp;&nbsp;';
        return html;
    }
    //弹出检验证书窗口
    user.ToolMangement = function(no){
        setTimeout(function(){
            $("#no2").val(no);
            $("#ToolDialog").modal("show");
            res.loadCheckList(no);//检验信息工具数据列表
        },100)
    }
    //检验工具信息列表
    res.loadCheckList=function(toolNo){
        $('#ToolList').bootstrapTable('destroy');/*表格加载前先销毁原有数据*/
        $('#ToolList').bootstrapTable({
            method: 'POST',
            url:"../toolController/getInspectionCertificates",
            queryParamsType:'',
            queryParams:function (params) {
                pageSize = params.pageSize;
                pageNum = params.pageNumber;
                return {
                    rows:pageSize,
                    page:pageNum,
                    toolNo:toolNo
                }
            },
            contentType:"application/x-www-form-urlencoded; charset=UTF-8",
            cache: false,     // 不缓存
            striped: true,    // 隔行加亮
            pagination: true, //是否显示分页
            toolbar: '',//工具列
            singleSelect:true, //单选
            clickToSelect:true,
            pageSize: 10,
            pageNumber: 1,     //初始化加载第一页，默认第一页
            pageList: [5, 10, 20, 30, 50], //可供选择的每页的行数（*）
            sidePagination: "server",
            search: false,
            showRefresh: true,  //是否显示刷新按钮
            clickToSelect: true,  //是否启用点击选中行
            columns:[
                {field: "select",title: "选择",checkbox: true,width: 60},
                {field: '',title: '序号',width: 60,align:"center",valign:"middle",formatter: function (value, row, index) {return index+1;}},
                {field:"no",title:"证书编号",align:"center",valign:"middle",sortable:"true"},
                {field:"issuedDate",title:"发证日期",align:"center",valign:"middle",sortable:"true",formatter: function (value) {
                    if(value==""||value==null){
                        return "";
                    }else{
                        var values = new Date(value).Format("yyyy-MM-dd");
                        return values;
                    }
                }},
                {field:"vaildTill",title:"有效期至",align:"center",valign:"middle",sortable:"true",formatter: function (value) {
                    if(value==""||value==null){
                        return "";
                    }else{
                        var values = new Date(value).Format("yyyy-MM-dd");
                        return values;
                    }
                }},
                // {field:"issuedBy",title:"授权签字人",align:"center",valign:"middle",sortable:"true"},
                // {field:"status",title:"证书状态",align:"center",valign:"middle",sortable:"true",formatter: function (value) {
                //     if(value == 0){
                //         return "正常"
                //     }else{
                //         return "过期"
                //     }}
                // },
                {field:"cz",title:"操作",align:"center",valign:"middle",width:180,formatter: res.optionsFormatter}
            ],
            onClickRow:function(row,ele){
            },
            formatLoadingMessage: function () {
                return "请稍等，正在加载中...";
            },
            formatNoMatches: function () {
                return '无符合条件的记录';
            },
            responseHandler: function(res) {
                var total ,rows;
                if (res!=null&&res.length!=0) {
                    total = res[0].total;
                    rows = res;
                }else {
                    total = 0;
                    rows = new Array();
                }
                return {
                    "total":total,//total,//总页数
                    "rows":rows  //数据
                };
            }
        });
    };
    //操作按钮
    res.optionsFormatter = function (value,row) {
        var html = '<button type="button" class="btn btn-info" title="查看附件" onclick="user.fileCheckMangement(\''+row.no+'\',\''+row.attachment+'\')" > <span class="glyphicon glyphicon-folder-open"></span></button>&nbsp;&nbsp;&nbsp;&nbsp;';
        return html;
    }
    //查看附件
    user.fileCheckMangement = function(no,attachment){
        var reg =  /\.(?:pdf)$/i;   //用于验证图片扩展名的正则表达式
        if(reg.test(attachment)){   //如果是PDF文件
            setTimeout(function(){
                $("#pdfBox").modal("show");
                user.pdfChk(no);
            },100)
        }else{
            setTimeout(function(){
                //显示图片需要的参数
                $("#fileImg").val(attachment);
                $("#noimg").val(no);
                if(attachment == ""||attachment==null ||attachment==undefined){
                    layer.msg("该证书没有附件，不能查看");
                    return false;
                }
                $("#fileCheckModal").modal("show");
                res.fileImg(no);//显示图片
            },100);
        }
    }
    user.pdfChk = function(no){  //显示pdf文件
        $.ajax({
            url:"../inspec/ck",
            type:"post",
            data:{"no":no},
            dataType:"json",
            success:function(data){
                $("#media").attr('href',data.mess);
                $('#media').media({width:800, height:600});
            }
        })
    }
    //读取图片
    res.fileImg = function(no){
        var noImg = $("#noimg").val();
        var result = document.getElementById("result");
        var input = document.getElementById("fileImg");
        if(typeof FileReader==='undefined'){
            result.innerHTML = "抱歉，你的浏览器不支持 FileReader";
            input.setAttribute('disabled','disabled');
        }else{
            $.ajax({
                url:"../inspec/ck",
                type:"post",
                data:{"no":noImg},
                dataType:"json",
                success:function(data){
                    var ImgSrc =data.mess;
                    $("#image").attr('src',ImgSrc);
                    $("#file_show .down_img").attr('href',ImgSrc);
                    $("#file_show .down_img").attr('download',ImgSrc);
                    res.bigPic();//点击显示大图
                }
            });
        }
    }
    //显示大图
    res.bigPic = function(){
        $("#image").click(function () {
            var _this = $(this);//将当前的pimg元素作为_this传入函数
            res.imgShow("#outerdiv", "#innerdiv", "#bigimg", _this);
        })
    }
    res.imgShow = function(outerdiv, innerdiv, bigimg, _this){
        var src = _this.attr("src");//获取当前点击的pimg元素中的src属性
        $(bigimg).attr("src", src);//设置#bigimg元素的src属性
        /*获取当前点击图片的真实大小，并显示弹出层及大图*/
        $("<img/>").attr("src", src).load(function(){
            var windowW = $(window).width();//获取当前窗口宽度
            var windowH = $(window).height();//获取当前窗口高度
            var realWidth = this.width;//获取图片真实宽度
            var realHeight = this.height;//获取图片真实高度
            var imgWidth, imgHeight;
            var scale = 0.8;//缩放尺寸，当图片真实宽度和高度大于窗口宽度和高度时进行缩放

            if(realHeight>windowH*scale) {//判断图片高度
                imgHeight = windowH*scale;//如大于窗口高度，图片高度进行缩放
                imgWidth = imgHeight/realHeight*realWidth;//等比例缩放宽度
                if(imgWidth>windowW*scale) {//如宽度扔大于窗口宽度
                    imgWidth = windowW*scale;//再对宽度进行缩放
                }
            } else if(realWidth>windowW*scale) {//如图片高度合适，判断图片宽度
                imgWidth = windowW*scale;//如大于窗口宽度，图片宽度进行缩放
                imgHeight = imgWidth/realWidth*realHeight;//等比例缩放高度
            } else {//如果图片真实高度和宽度都符合要求，高宽不变
                imgWidth = realWidth;
                imgHeight = realHeight;
            }
            $(bigimg).css("width",imgWidth);//以最终的宽度对图片缩放
            var w = (windowW-imgWidth)/2;//计算图片与窗口左边距
            var h = (windowH-imgHeight)/2;//计算图片与窗口上边距
            $(innerdiv).css({"top":h, "left":w});//设置#innerdiv的top和left属性
            $(outerdiv).fadeIn("fast");//淡入显示#outerdiv及.pimg
        });

        $(outerdiv).click(function(){//再次点击淡出消失弹出层
            $(this).fadeOut("fast");
        });
    }
    //工具类型接口
    res.turnType = function(){
        $('#turnType').selectpicker('refresh');//刷新下拉框
        $("#dimension").selectpicker('refresh');//刷新下拉框
        $('#status').selectpicker('refresh');//刷新下拉框
        $("#base").selectpicker('refresh');//刷新下拉框
        /* 页面加载获取产品下拉框数据 */
        var tool_type = 'tool_type';
        var tool_status = 'tool_status';
        var base = 'base';
        var tool_dimension = 'tool_dimension';
        res.selecAjax(tool_type);
        res.selecAjax(tool_status);
        res.selecAjax(base);
        res.selecAjax(tool_dimension);
    }
    //调用下拉框ajax方法
    res.selecAjax = function(item){
        $.ajax({
            type: "POST",
            data:{
                parentcode:item,
                tool:'123'
            },
            async:true,
            url: '../sysCodeListController/getSysCodeList',
            success:function(res){
                var res = res.data;
                var txt ='<option value="" selected="true" disabled="true">请选择</option>';
                var txt1='<option value="" selected="true" disabled="true">请选择</option>';
                var txt2='<option value="" selected="true" disabled="true">请选择</option>';
                var txt3='<option value="" selected="true" disabled="true">请选择</option>';
                for(var i = 0;i <res.length;i++){
                    if(res[i].parentcode == "tool_type"){
                        txt += '<option value="' + res[i].id + '">' + res[i].name +'</option>';
                        $('#turnType').html(txt);
                        $('#turnType').selectpicker('refresh');
                    }else if(res[i].parentcode == "tool_status"){
                        txt1 += '<option value="' + res[i].id + '">' + res[i].name +'</option>';
                        $('#status').html(txt1);
                        $('#status').selectpicker('refresh');
                    }else if(res[i].parentcode == "base"){
                        txt2 += '<option value="' + res[i].id + '">' + res[i].name +'</option>';
                        $('#base').html(txt2);
                        $('#base').selectpicker('refresh');
                    }else if(res[i].parentcode == "tool_dimension"){
                        txt3 += '<option value="' + res[i].id + '">' + res[i].name +'</option>';
                        $('#dimension').html(txt3);
                        $('#dimension').selectpicker('refresh');
                    }
                }
            }
        });
    }
    //初始化工具类型接口
    res.turnOrganze = function(){
        $('#turnType').selectpicker('refresh');//刷新下拉框
        $('#statusTurn').selectpicker('refresh');//刷新下拉框
        $("#baseTurn").selectpicker('refresh');//刷新下拉框
        /* 页面加载获取产品下拉框数据 */
        var tool_type = 'tool_type';
        var tool_status = 'tool_status';
        var base = 'base';
        var tool_dimension = 'tool_dimension';
        res.selecAjax1(tool_type);
        res.selecAjax1(tool_status);
        res.selecAjax1(base);
        res.selecAjax1(tool_dimension);
    }
    //初始化调用下拉框ajax方法
    res.selecAjax1 = function(item){
        $.ajax({
            type: "POST",
            data:{
                parentcode:item,
                tool:'123'
            },
            async:true,
            url: '../sysCodeListController/getSysCodeList',
            success:function(res){
                var res = res.data;
                var txt ='<option value="" selected="true" disabled="true">请选择</option>';
                var txt1='<option value="" selected="true" disabled="true">请选择</option>';
                var txt2='<option value="" selected="true" disabled="true">请选择</option>';
                for(var i = 0;i <res.length;i++){
                    if(res[i].parentcode == "tool_type"){
                        txt += '<option  value="' + res[i].id + '">' + res[i].name +'</option>';
                        $('#typeTurn').html(txt);
                        $('#typeTurn').selectpicker('refresh');
                    }else if(res[i].parentcode == "tool_status"){
                        txt1 += '<option value="' + res[i].id + '">' + res[i].name +'</option>';
                        $('#statusTurn').html(txt1);
                        $('#statusTurn').selectpicker('refresh');
                    }else if(res[i].parentcode == "base"){
                        txt2 += '<option value="' + res[i].id + '">' + res[i].name +'</option>';
                        $('#baseTurn').html(txt2);
                        $('#baseTurn').selectpicker('refresh');
                    }
                }
            }
        });
    }
    //调用时间插件
    res.layerDate = function(){
        laydate.skin('molv');/* 设置时间插件的皮肤 */
        var start = {
            elem: '#manufactureDate', //选择ID为START的input
            format: 'YYYY-MM-DD', //自动生成的时间格式
            max: laydate.now(), //最大日期
            istoday: false,  //是否是当天
            start: laydate.now(0,"YYYY-MM-DD"),  //设置开始时间为当前时间
        };
        laydate(start);
    }
    //修改用户信息
    res.openUpdateTurn=function(){
        var $form = $('#addTurnForm');
        var datas = $form.data('bootstrapValidator');
        if (datas) {
            // 修复记忆的组件不验证
            datas.validate();
            if (!datas.isValid()) {
                return false;
            }
        }
        res.resetValidator();
        //获取当前选中的数据
        var rows = $("#turnOverList").bootstrapTable('getSelections');
        if (rows.length > 0){
            //打开修改窗口并初始化数据
            $("#addUserDialog").modal("show");
            $("#changeUser").html("修改周转工具");

            $("#id").val(rows[0].id);
            $('.selectpicker').selectpicker('refresh');
            var select_turnType = rows[0].type;
            res.showData(select_turnType,'tool_type');

            var select_dimension = rows[0].dimension;
            res.showData1(select_dimension,'tool_dimension');

            var select_status = rows[0].status;
            res.showData2(select_status,'tool_status');

            var select_base = rows[0].base;
            res.showData3(select_base,'base');

            $("#toolName").val(rows[0].toolName);
            $("#noTurn").val(rows[0].no);
            $("#deadWeight").val(rows[0].deadWeight);
            $("#safeLoad").val(rows[0].safeLoad);

            $("#manufactureDate").val(res.dateFormat(new Date(rows[0].manufactureDate).getTime(),"yyyy-MM-dd"));
            $("#remark").val(rows[0].remark);
            $("#deviceId").val(rows[0].deviceId);
        }else{
            layer.alert("请选中一行数据！", {icon: 3});
        }
    };
    //工具类型下拉框数据回显
    res.showData = function(items,tool_type){
        $.ajax({
            type: "POST",
            data:{
                parentcode:tool_type,
                tool:'123'
            },
            async:true,
            url: '../sysCodeListController/getSysCodeList',
            success:function(res){
                var res = res.data;
                var txt;
                txt='<option value="0" disabled="true">请选择</option>';
                for(var i = 0;i <res.length;i++){
                    if(items == res[i].name){
                        txt += '<option value="' + res[i].id + '" selected="true">' + res[i].name +'</option>';
                    }else{
                        txt += '<option value="' + res[i].id + '">' + res[i].name +'</option>';
                    }
                }
                $('#turnType').html(txt);
                $('#turnType').selectpicker('refresh');
            }
        });
    }
    //尺寸工具类型下拉框数据回显
    res.showData1 = function(items,tool_dimension){
        $.ajax({
            type: "POST",
            data:{
                parentcode:tool_dimension,
                tool:'123'
            },
            async:true,
            url: '../sysCodeListController/getSysCodeList',
            success:function(res){
                var res = res.data;
                var txt;
                txt='<option value="0" disabled="true">请选择</option>';
                for(var i = 0;i <res.length;i++){
                    if(items == res[i].name){
                        txt += '<option value="' + res[i].id + '" selected="true">' + res[i].name +'</option>';
                    }else{
                        txt += '<option value="' + res[i].id + '">' + res[i].name +'</option>';
                    }
                }
                $('#dimension').html(txt);
                $('#dimension').selectpicker('refresh');
            }
        });
    }
    //状态下拉框数据回显
    res.showData2 = function(items,tool_status){
        $.ajax({
            type: "POST",
            data:{
                parentcode:tool_status,
                tool:'123'
            },
            async:true,
            url: '../sysCodeListController/getSysCodeList',
            success:function(res){
                var res = res.data;
                var txt;
                txt='<option value="0" disabled="true">请选择</option>';
                for(var i = 0;i <res.length;i++){
                    if(items == res[i].name){
                        txt += '<option value="' + res[i].id + '" selected="true">' + res[i].name +'</option>';
                    }else{
                        txt += '<option value="' + res[i].id + '">' + res[i].name +'</option>';
                    }
                }
                $('#status').html(txt);
                $('#status').selectpicker('refresh');
            }
        });
    }
    //归属地下拉框数据回显
    res.showData3 = function(items,base){
        $.ajax({
            type: "POST",
            data:{
                parentcode:base,
                tool:'123'
            },
            async:true,
            url: '../sysCodeListController/getSysCodeList',
            success:function(res){
                var res = res.data;
                var txt;
                txt='<option value="0" disabled="true">请选择</option>';
                for(var i = 0;i <res.length;i++){
                    if(items == res[i].name){
                        txt += '<option value="' + res[i].id + '" selected="true">' + res[i].name +'</option>';
                    }else{
                        txt += '<option value="' + res[i].id + '">' + res[i].name +'</option>';
                    }
                }
                $('#base').html(txt);
                $('#base').selectpicker('refresh');
            }
        });
    }
    //删除用户函数
    res.deleteTurn=function(){
        var rows = $("#turnOverList").bootstrapTable('getSelections');
        if (rows.length>0){
            var row = rows[0];
            layer.confirm('您确定要删除此记录吗？', {
                btn: ['确定','取消'] //按钮
            }, function(){
                $.ajax({
                    url:"../toolController/deleteTool",
                    type:"post",
                    data:{"no":row.no},
                    dataType:"json",
                    success:function(data){
                        if (data.code==0){
                            layer.msg(data.msg);
                            $("#turnOverList").bootstrapTable("refresh");
                        }else{
                            layer.msg(data.msg);
                        }
                    }
                });
            });
        }else{
            layer.alert("请选中一行数据！", {icon: 3});
        }
    };
    //点击搜索查询
    res.searchTurn = function () {
        $("#searchTools").click(function(){
            var type = $("#typeTurn").val();
            var toolName = $("#toolNameTurn").val();
            var status = $("#statusTurn").val();
            var base = $("#baseTurn").val();
            var numberTurn = $("#noTurns").val();
            res.loadTurnList(type,toolName,base,status,numberTurn);
        });
    }
    /*模板下载按钮点击事件*/
    res.uploadExcel = function(){
        $.ajax({
            type:"post",
            url:"../toolController/getExcelPath",
            data:{"type":"周转工具导入模板"},
            success:function(res){
                if(res.code== 0){
                    window.location.href = res.data;
                }
            }
        })
    }
    /*时间戳格式化*/
    res.dateFormat=function (now,mask) {
        var d = new Date(now);
        var zeroize = function (value, length)
        {
            if (!length) length = 2;
            value = String(value);
            for (var i = 0, zeros = ''; i < (length - value.length); i++)
            {
                zeros += '0';
            }
            return zeros + value;
        };

        return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function ($0)
        {
            switch ($0)
            {
                case 'd': return d.getDate();
                case 'dd': return zeroize(d.getDate());
                case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];
                case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()];
                case 'M': return d.getMonth() + 1;
                case 'MM': return zeroize(d.getMonth() + 1);
                case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
                case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()];
                case 'yy': return String(d.getFullYear()).substr(2);
                case 'yyyy': return d.getFullYear();
                case 'h': return d.getHours() % 12 || 12;
                case 'hh': return zeroize(d.getHours() % 12 || 12);
                case 'H': return d.getHours();
                case 'HH': return zeroize(d.getHours());
                case 'm': return d.getMinutes();
                case 'mm': return zeroize(d.getMinutes());
                case 's': return d.getSeconds();
                case 'ss': return zeroize(d.getSeconds());
                case 'l': return zeroize(d.getMilliseconds(), 3);
                case 'L': var m = d.getMilliseconds();
                    if (m > 99) m = Math.round(m / 10);
                    return zeroize(m);
                case 'tt': return d.getHours() < 12 ? 'am' : 'pm';
                case 'TT': return d.getHours() < 12 ? 'AM' : 'PM';
                case 'Z': return d.toUTCString().match(/[A-Z]+$/);
                // Return quoted strings with the surrounding quotes removed
                default: return $0.substr(1, $0.length - 2);
            }
        });
    }
})(user);
// 对Date的扩展，将 Date 转化为指定格式的String
Date.prototype.Format = function (fmt) { //author: zhengsh 2016-9-5
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


